import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 当事人端路由
const clientRoutes = [
  {
    path: '/client',
    component: () => import('@/layouts/ClientLayout.vue'),
    children: [
      {
        path: '',
        name: 'ClientHome',
        component: () => import('@/pages/client/Home.vue')
      },
      {
        path: 'case/:id/timeline',
        name: 'ClientCaseTimeline',
        component: () => import('@/pages/client/CaseTimeline.vue')
      },
      {
        path: 'case-documents',
        name: 'ClientCaseDocuments',
        component: () => import('@/pages/client/CaseDocuments.vue')
      },
      {
        path: 'appointments',
        name: 'ClientAppointments',
        component: () => import('@/pages/client/Appointments.vue')
      },
      {
        path: 'points',
        name: 'ClientPoints',
        component: () => import('@/pages/client/PointsMall.vue')
      },
      {
        path: 'cases',
        name: 'ClientCaseLibrary',
        component: () => import('@/pages/client/CaseLibrary.vue')
      },
      {
        path: 'intelligent-qa',
        name: 'ClientIntelligentQA',
        component: () => import('@/pages/client/IntelligentQA.vue')
      },
      {
        path: 'case-timeline',
        name: 'ClientCaseTimelineOverview',
        component: () => import('@/pages/client/CaseTimeline.vue')
      },
      {
        path: 'notifications',
        name: 'ClientNotifications',
        component: () => import('@/pages/client/Notifications.vue')
      },
      {
        path: 'help',
        name: 'ClientHelp',
        component: () => import('@/pages/client/Help.vue')
      },
      {
        path: 'profile',
        name: 'ClientProfile',
        component: () => import('@/pages/client/Profile.vue')
      },
      {
        path: 'case-evaluation/:caseNumber',
        name: 'ClientCaseEvaluation',
        component: () => import('@/pages/client/CaseEvaluation.vue')
      },
      {
        path: 'lawyer-contact',
        name: 'ClientLawyerContact',
        component: () => import('@/pages/client/LawyerContact.vue')
      }
    ]
  }
]

// 律师端路由
const lawyerRoutes = [
  {
    path: '/lawyer',
    component: () => import('@/layouts/LawyerLayout.vue'),
    children: [
      {
        path: '',
        name: 'LawyerHome',
        component: () => import('@/pages/lawyer/Home.vue')
      },
      {
        path: 'cases',
        name: 'LawyerCaseManagement',
        component: () => import('@/pages/lawyer/CaseManagement.vue')
      },
      {
        path: 'case/:id',
        name: 'LawyerCaseDetail',
        component: () => import('@/pages/lawyer/CaseDetail.vue')
      },
      {
        path: 'case/:id/edit',
        name: 'LawyerCaseEdit',
        component: () => import('@/pages/lawyer/CaseEdit.vue')
      },
      {
        path: 'appraisal',
        name: 'LawyerAppraisal',
        component: () => import('@/pages/lawyer/AppraisalManagement.vue')
      },
      {
        path: 'appointments',
        name: 'LawyerAppointments',
        component: () => import('@/pages/lawyer/AppointmentManagement.vue')
      },
      {
        path: 'cases/library',
        name: 'LawyerCaseLibrary',
        component: () => import('@/pages/lawyer/CaseLibrary.vue')
      },
      {
        path: 'templates',
        name: 'LawyerDocumentTemplates',
        component: () => import('@/pages/lawyer/DocumentTemplates.vue')
      },
      {
        path: 'statistics',
        name: 'LawyerStatistics',
        component: () => import('@/pages/lawyer/Statistics.vue')
      },
      {
        path: 'case-filing-assistance',
        name: 'LawyerCaseFilingAssistance',
        component: () => import('@/pages/lawyer/CaseFilingAssistance.vue')
      },
      {
        path: 'case-filing-detail/:caseNumber',
        name: 'LawyerCaseFilingDetail',
        component: () => import('@/pages/lawyer/CaseFilingDetail.vue')
      },
      {
        path: 'case-filing-progress',
        name: 'LawyerCaseFilingProgress',
        component: () => import('@/pages/lawyer/CaseFilingProgress.vue')
      },
      {
        path: 'intelligent-qa',
        name: 'LawyerIntelligentQA',
        component: () => import('@/pages/lawyer/IntelligentQA.vue')
      }
    ]
  }
]

// 市场部路由
const marketingRoutes = [
  {
    path: '/marketing',
    component: () => import('@/layouts/MarketingLayout.vue'),
    children: [
      {
        path: '',
        name: 'MarketingHome',
        component: () => import('@/pages/marketing/Home.vue')
      },
      {
        path: 'enterprise',
        name: 'MarketingEnterpriseDisplay',
        component: () => import('@/pages/marketing/EnterpriseDisplay.vue')
      },
      {
        path: 'case/create',
        name: 'MarketingCaseCreation',
        component: () => import('@/pages/marketing/CaseCreation.vue')
      },
      {
        path: 'contract/signing',
        name: 'MarketingContractSigning',
        component: () => import('@/pages/marketing/ContractSigning.vue')
      },
      {
        path: 'cases',
        name: 'MarketingCaseCenter',
        component: () => import('@/pages/marketing/CaseCenter.vue')
      },
      {
        path: 'qa',
        name: 'MarketingQA',
        component: () => import('@/pages/marketing/IntelligentQA.vue')
      },
      {
        path: 'profile',
        name: 'MarketingProfile',
        component: () => import('@/pages/marketing/Profile.vue')
      }
    ]
  }
]

// 审核部路由
const financeRoutes = [
  {
    path: '/finance',
    component: () => import('@/layouts/FinanceLayout.vue'),
    children: [
      {
        path: '',
        name: 'AuditHome',
        component: () => import('@/pages/finance/Home.vue')
      },
      {
        path: 'filing-approval',
        name: 'FilingApproval',
        component: () => import('@/pages/finance/FilingApproval.vue')
      },
      {
        path: 'archive-approval',
        name: 'ArchiveApproval',
        component: () => import('@/pages/finance/ArchiveApproval.vue')
      },
      {
        path: 'statistics',
        name: 'AuditStatistics',
        component: () => import('@/pages/finance/Statistics.vue')
      }
    ]
  }
]

// 鉴定部路由
const appraisalRoutes = [
  {
    path: '/appraisal',
    component: () => import('@/layouts/AppraisalLayout.vue'),
    children: [
      {
        path: '',
        name: 'AppraisalHome',
        component: () => import('@/pages/appraisal/Home.vue')
      },
      {
        path: 'cases',
        name: 'AppraisalCaseManagement',
        component: () => import('@/pages/appraisal/CaseManagement.vue')
      },
      {
        path: 'pending',
        name: 'AppraisalPending',
        component: () => import('@/pages/appraisal/PendingCases.vue')
      },
      {
        path: 'identification/:id',
        name: 'IdentificationProcess',
        component: () => import('@/pages/appraisal/IdentificationProcess.vue')
      },
      {
        path: 'completed',
        name: 'AppraisalCompleted',
        component: () => import('@/pages/appraisal/CompletedCases.vue')
      },
      {
        path: 'case/:id',
        name: 'AppraisalCaseDetail',
        component: () => import('@/pages/appraisal/CaseDetail.vue')
      },
      {
        path: 'date-management',
        name: 'AppraisalDateManagement',
        component: () => import('@/pages/appraisal/DateManagement.vue')
      }
    ]
  }
]

// 管理员路由
const adminRoutes = [
  {
    path: '/admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    children: [
      {
        path: '',
        name: 'AdminHome',
        component: () => import('@/pages/admin/Home.vue')
      },
      {
        path: 'statistics',
        name: 'AdminStatistics',
        component: () => import('@/pages/admin/Statistics.vue')
      },
      {
        path: 'cases/library',
        name: 'AdminCaseLibrary',
        component: () => import('@/pages/admin/CaseLibrary.vue')
      },
      {
        path: 'business',
        name: 'AdminBusiness',
        component: () => import('@/pages/admin/BusinessManagement.vue')
      },
      {
        path: 'clients',
        name: 'AdminClients',
        component: () => import('@/pages/admin/ClientManagement.vue')
      },
      {
        path: 'points',
        name: 'AdminPoints',
        component: () => import('@/pages/admin/PointsManagement.vue')
      },
      {
        path: 'logs',
        name: 'AdminLogs',
        component: () => import('@/pages/admin/LogManagement.vue')
      },
      {
        path: 'knowledge',
        name: 'AdminKnowledge',
        component: () => import('@/pages/admin/KnowledgeManagement.vue')
      },
      {
        path: 'workflow-settings',
        name: 'WorkflowSettings',
        component: () => import('@/pages/admin/WorkflowSettings.vue')
      },
      {
        path: 'cases',
        name: 'AdminCaseManagement',
        component: () => import('@/pages/admin/CaseManagement.vue')
      },
      {
        path: 'lawyers',
        name: 'AdminLawyerManagement',
        component: () => import('@/pages/admin/LawyerManagement.vue')
      },
      {
        path: 'users',
        name: 'AdminUserManagement',
        component: () => import('@/pages/admin/UserManagement.vue')
      },
      {
        path: 'business/detail/:id',
        name: 'AdminBusinessDetail',
        component: () => import('@/pages/admin/BusinessDetail.vue')
      },
      {
        path: 'business/edit/:id',
        name: 'AdminBusinessEdit',
        component: () => import('@/pages/admin/BusinessEdit.vue')
      },
      {
        path: 'lawyer-cases',
        name: 'AdminLawyerCaseOverview',
        component: () => import('@/pages/admin/LawyerCaseOverview.vue')
      },
      {
        path: 'lawyer/:lawyerId/cases',
        name: 'AdminLawyerCaseDetail',
        component: () => import('@/pages/admin/LawyerCaseDetail.vue')
      },
      {
        path: 'case-review-process',
        name: 'AdminCaseReviewProcess',
        component: () => import('@/pages/admin/CaseReviewProcess.vue')
      },
      {
        path: 'case-auto-demo',
        name: 'AdminCaseAutoDemo',
        component: () => import('@/pages/admin/CaseAutoDemo.vue')
      },
      {
        path: 'overdue-reminder',
        name: 'AdminOverdueReminder',
        component: () => import('@/pages/admin/OverdueReminder.vue')
      },
      {
        path: 'electronic-banner',
        name: 'AdminElectronicBanner',
        component: () => import('@/pages/admin/ElectronicBanner.vue')
      }
    ]
  }
]

// 公共路由
const publicRoutes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/pages/Register.vue')
  }
]

// 路由守卫
const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...publicRoutes,
    ...clientRoutes,
    ...lawyerRoutes,
    ...marketingRoutes,
    ...financeRoutes,
    ...appraisalRoutes,
    ...adminRoutes
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 公共路由不需要验证
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }
  
  // 检查是否已登录
  if (!userStore.isLoggedIn) {
    // 开发环境下自动设置测试用户
    if (import.meta.env.DEV) {
      // 根据访问路径自动设置角色
      let testRole = 'client'
      if (to.path.startsWith('/lawyer')) testRole = 'lawyer'
      else if (to.path.startsWith('/admin')) testRole = 'admin'
      else if (to.path.startsWith('/marketing')) testRole = 'marketing'
      else if (to.path.startsWith('/finance')) testRole = 'finance'
      else if (to.path.startsWith('/appraisal')) testRole = 'appraisal'
      
      userStore.login({
        userInfo: { name: `测试${testRole}用户`, id: 1 },
        token: 'test-token',
        role: testRole
      })
    } else {
      next('/login')
      return
    }
  }
  
  // 根据角色检查权限
  const path = to.path
  const role = userStore.role
  
  // 角色权限映射
  const rolePermissions = {
    client: ['/client'],
    lawyer: ['/lawyer'],
    marketing: ['/marketing'],
    finance: ['/finance'],
    appraisal: ['/appraisal'],
    admin: ['/admin']
  }
  
  // 检查用户是否有权限访问该路径
  const allowedPaths = rolePermissions[role] || []
  const hasPermission = allowedPaths.some(allowedPath => path.startsWith(allowedPath))
  
  if (!hasPermission) {
    // 重定向到用户角色的首页
    const redirectPath = allowedPaths[0] || '/login'
    next(redirectPath)
    return
  }
  
  next()
})

export default router 